<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 用户角色管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        /* 自定义样式 */
        .btn {
            transition: all 0.3s ease;
        }

        .btn:hover {
            transform: scale(1.05);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 400px;
        }

        .pagination-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    </style>
</head>

<body class="bg-gray-100">
<!-- 顶部操作栏 -->
<div class="fixed top-0 left-0 right-0 bg-white shadow-md p-4 flex justify-between items-center">
    <h1 class="text-2xl font-bold">后台管理系统</h1>
</div>

<!-- 中间内容区域 -->
<div class="pt-16 p-4">
    <div class="flex justify-between items-center mb-4">
        <div>
            <button id="addRoleBtn" class="btn bg-blue-600 text-white py-2 px-4 rounded-md">添加角色</button>
        </div>
        <div class="flex items-center">
            <input type="text" id="searchRoleName" placeholder="按角色名称查询"
                   class="border border-gray-300 py-2 px-4 rounded-md mr-2">
            <button id="searchBtn" class="btn bg-green-600 text-white py-2 px-4 rounded-md">查询</button>
        </div>
    </div>
    <!-- 表格 -->
    <table class="w-full border-collapse border border-gray-300">
        <thead>
        <tr class="bg-gray-200">
            <th class="border border-gray-300 p-2">Role ID</th>
            <th class="border border-gray-300 p-2">Role Name</th>
            <th class="border border-gray-300 p-2">Description</th>
            <th class="border border-gray-300 p-2">操作</th>
        </tr>
        </thead>
        <tbody id="roleTableBody">
        <!-- 动态填充表格数据 -->
        </tbody>
    </table>
    <!-- 分页控件 -->
    <div class="mt-4 flex justify-between items-center">
        <div>
            <p>共 <span id="recordCount">0</span> 条记录</p>
        </div>
        <div class="flex items-center">
            <button id="prevPageBtn" class="pagination-btn btn bg-gray-200 text-gray-700 py-1 px-3 rounded-md mr-2">
                <i class="fas fa-chevron-left"></i> 上一页
            </button>
            <span id="currentPageInfo" class="mx-2">第 1 页 / 共 1 页</span>
            <button id="nextPageBtn" class="pagination-btn btn bg-gray-200 text-gray-700 py-1 px-3 rounded-md ml-2">
                下一页 <i class="fas fa-chevron-right"></i>
            </button>
        </div>
    </div>
</div>

<!-- 添加角色弹窗 -->
<div id="addRoleModal" class="modal">
    <div class="modal-content">
        <h2 class="text-xl font-bold mb-4">添加角色</h2>
        <form id="addRoleForm">
            <div class="mb-4">
                <label for="addRoleName" class="block text-sm font-medium text-gray-700">Role Name</label>
                <input type="text" id="addRoleName" name="roleName"
                       class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
            </div>
            <div class="mb-4">
                <label for="addDescription" class="block text-sm font-medium text-gray-700">Description</label>
                <textarea id="addDescription" name="description" rows="3"
                          class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"></textarea>
            </div>
            <div class="flex justify-end">
                <button type="submit" class="btn bg-blue-600 text-white py-2 px-4 rounded-md">保存</button>
                <button type="button" id="addCancelBtn"
                        class="btn bg-gray-500 text-white py-2 px-4 rounded-md mr-2">取消</button>
            </div>
        </form>
    </div>
</div>

<!-- 修改角色弹窗 -->
<div id="editRoleModal" class="modal">
    <div class="modal-content">
        <h2 class="text-xl font-bold mb-4">修改角色</h2>
        <form id="editRoleForm">
            <input type="hidden" id="editRoleId" name="用户ID">
            <div class="mb-4">
                <label for="editRoleName" class="block text-sm font-medium text-gray-700">Role Name</label>
                <input type="text" id="editRoleName" name="用户名称"
                       class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
            </div>
            <div class="mb-4">
                <label for="editDescription" class="block text-sm font-medium text-gray-700">Description</label>
                <textarea id="editDescription" name="描述" rows="3"
                          class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"></textarea>
            </div>
            <div class="flex justify-end">
                <button type="submit" class="btn bg-green-600 text-white py-2 px-4 rounded-md">保存修改</button>
                <button type="button" id="editCancelBtn"
                        class="btn bg-gray-500 text-white py-2 px-4 rounded-md mr-2">取消</button>
            </div>
        </form>
    </div>
</div>

<!-- 删除角色确认弹窗 -->
<div id="deleteRoleModal" class="modal">
    <div class="modal-content">
        <h2 class="text-xl font-bold mb-4">删除角色</h2>
        <p>确定要删除该角色吗？</p>
        <div class="flex justify-end mt-4">
            <button type="button" id="deleteConfirmBtn"
                    class="btn bg-red-600 text-white py-2 px-4 rounded-md">确定</button>
            <button type="button" id="deleteCancelBtn"
                    class="btn bg-gray-500 text-white py-2 px-4 rounded-md mr-2">取消</button>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 分页相关变量
        let currentPage = 1;
        let totalPages = 1;
        let pageSize = 5; // 每页显示的记录数，现在改名为size
        let currentRoleName = ''; // 当前搜索的角色名称

        // 初始化数据
        function loadRoles(roleName = '', page = 1) {
            currentPage = page;
            currentRoleName = roleName;

            $.ajax({
                url: `/sysRole/pageRole?roleName=${roleName}&current=${page}&size=${pageSize}`, // 修改URL参数为current和size
                type: 'GET',
                success: function (response) {
                    $('#roleTableBody').empty();

                    // 假设后端返回的数据结构包含 records, totalRecords
                    const records = response.records || [];
                    const totalRecords = response.total || 0;

                    $('#recordCount').text(totalRecords);

                    // 计算总页数
                    totalPages = Math.ceil(totalRecords / pageSize);
                    updatePaginationInfo();

                    // 更新分页按钮状态
                    updatePaginationButtons();

                    // 填充表格数据
                    records.forEach(function (role) {
                        var row = `<tr>
                                <td class="border border-gray-300 p-2">${role.roleId}</td>
                                <td class="border border-gray-300 p-2">${role.roleName}</td>
                                <td class="border border-gray-300 p-2">${role.description || 'null'}</td>
                                <td class="border border-gray-300 p-2">
                                    <button class="btn bg-green-600 text-white py-1 px-2 rounded-md mr-2 editBtn" data-id="${role.roleId}">修改</button>
                                    <button class="btn bg-red-600 text-white py-1 px-2 rounded-md deleteBtn" data-id="${role.roleId}">删除</button>
                                </td>
                            </tr>`;
                        $('#roleTableBody').append(row);
                    });
                },
                error: function (error) {
                    alert('加载角色数据失败: ' + error.responseText);
                }
            });
        }

        // 更新分页信息显示
        function updatePaginationInfo() {
            $('#currentPageInfo').text(`第 ${currentPage} 页 / 共 ${totalPages} 页`);
        }

        // 更新分页按钮状态
        function updatePaginationButtons() {
            $('#prevPageBtn').prop('disabled', currentPage <= 1);
            $('#nextPageBtn').prop('disabled', currentPage >= totalPages);
        }

        // 上一页按钮点击事件
        $('#prevPageBtn').on('click', function() {
            if (currentPage > 1) {
                loadRoles(currentRoleName, currentPage - 1);
            }
        });

        // 下一页按钮点击事件
        $('#nextPageBtn').on('click', function() {
            if (currentPage < totalPages) {
                loadRoles(currentRoleName, currentPage + 1);
            }
        });

        // 加载初始数据
        loadRoles();

        // 显示添加角色弹窗
        $('#addRoleBtn').on('click', function () {
            $('#addRoleModal').css('display', 'flex');
        });

        // 关闭添加角色弹窗
        $('#addCancelBtn').on('click', function () {
            $('#addRoleModal').css('display', 'none');
        });

        // 保存新角色
        $('#addRoleForm').on('submit', function (e) {
            e.preventDefault();
            var formData = {
                roleName: $('#addRoleName').val(),
                description: $('#addDescription').val()
            };
            $.ajax({
                url: '/sysRole/add',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (response) {
                    alert('保存成功');
                    $('#addRoleModal').css('display', 'none');
                    $('#addRoleForm')[0].reset();
                    // 重新加载当前页数据，如果添加后当前页已满则保持当前页，否则跳转到第一页
                    loadRoles(currentRoleName, Math.min(currentPage, totalPages));
                },
                error: function (error) {
                    alert('保存失败: ' + error.responseText);
                }
            });
        });

        // 显示修改角色弹窗
        $('#roleTableBody').on('click', '.editBtn', function () {
            var roleId = $(this).data('id');
            $.ajax({
                url: `/sysRole/${roleId}`,
                type: 'GET',
                success: function (role) {
                    $('#editRoleId').val(role.roleId);
                    $('#editRoleName').val(role.roleName);
                    $('#editDescription').val(role.description || '');
                    $('#editRoleModal').css('display', 'flex');
                },
                error: function (error) {
                    alert('获取角色信息失败: ' + error.responseText);
                }
            });
        });

        // 关闭修改角色弹窗
        $('#editCancelBtn').on('click', function () {
            $('#editRoleModal').css('display', 'none');
        });

        // 保存修改后的角色
        $('#editRoleForm').on('submit', function (e) {
            e.preventDefault();
            var formData = {
                roleId: $('#editRoleId').val(),
                roleName: $('#editRoleName').val(),
                description: $('#editDescription').val()
            };
            $.ajax({
                url: `/sysRole/${formData.roleId}`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (response) {
                    alert('修改成功');
                    $('#editRoleModal').css('display', 'none');
                    loadRoles(currentRoleName, currentPage); // 重新加载当前页数据
                },
                error: function (error) {
                    alert('修改失败: ' + error.responseText);
                }
            });
        });

        // 显示删除角色确认弹窗
        $('#roleTableBody').on('click', '.deleteBtn', function () {
            var roleId = $(this).data('id');
            $('#deleteRoleModal').data('roleId', roleId).css('display', 'flex');
        });

        // 关闭删除角色确认弹窗
        $('#deleteCancelBtn').on('click', function () {
            $('#deleteRoleModal').css('display', 'none');
        });

        // 确认删除角色
        $('#deleteConfirmBtn').on('click', function () {
            var roleId = $('#deleteRoleModal').data('roleId');
            $.ajax({
                url: `/sysRole/${roleId}`,
                type: 'DELETE',
                success: function (response) {
                    alert('删除成功');
                    $('#deleteRoleModal').css('display', 'none');
                    // 删除后检查当前页是否还有数据，如果没有则跳转到前一页
                    if ($('#roleTableBody').children().length === 0 && currentPage > 1) {
                        loadRoles(currentRoleName, currentPage - 1);
                    } else {
                        loadRoles(currentRoleName, currentPage);
                    }
                },
                error: function (error) {
                    alert('删除失败: ' + error.responseText);
                }
            });
        });

        // 按角色名称查询
        $('#searchBtn').on('click', function () {
            var roleName = $('#searchRoleName').val();
            loadRoles(roleName, 1); // 搜索时重置到第一页
        });
    });

</script>
</body>
</html>